<?php
/* 
	[BuyPg] (C) 2010-2011 Buypg
	$Id: common.php 2011-4-6 9:14:21 wufujun $
 */

if (!defined('THINK_PATH')){
	exit('Access Denied');
}


//系统扩展方法
load('extend');

//以下是项目公共方法

//SQL ADDSLASHES
function saddslashes($string) {
	if(is_array($string)) {
		foreach($string as $key => $val) {
			$string[$key] = saddslashes($val);
		}
	} else {
		$string = addslashes($string);
	}
	return $string;
}

//取消HTML代码
function shtmlspecialchars($string) {
	if(is_array($string)) {
		foreach($string as $key => $val) {
			$string[$key] = shtmlspecialchars($val);
		}
	} else {
		$string = preg_replace('/&amp;((#(\d{3,5}|x[a-fA-F0-9]{4})|[a-zA-Z][a-z0-9]{2,5});)/', '&\\1',
			str_replace(array('&', '"', '<', '>'), array('&amp;', '&quot;', '&lt;', '&gt;'), $string));
	}
	return $string;
}

//判断字符串是否存在
function strexists($haystack, $needle) {
	return !(strpos($haystack, $needle) === FALSE);
}

//判断跳转
function checkrefer($method, $url){
	if($method == 'GET'){
		cookie('_refer', rawurlencode($_SERVER['REQUEST_URI']));
	}else{
		cookie('_refer', rawurlencode($url));
	}
}

//获取用户信息
function getpassport($username,$password,$biz = 'user'){
	//判断是否是商户登录
	if($biz == 'user'){
		//非商户登录
		$DbUser = M("User");
		//判断用户名是否存在
		$arrUser = $DbUser->where("user_nickname = '$username'")->find();
		$passwordsha1 = sha1($password);
		if(empty($arrUser)){
			$status = -1;
		}elseif($arrUser['user_password'] != $passwordsha1){
			$status = -2;
		}else{
			$status = $arrUser['user_id'];
		}
		if($status > 0){
			$passport = array();
			$passport = $arrUser;
		}else{
			$passport = $status;
		}
	}elseif($biz == 'biz'){
		//商户登录
		$DbBiz = M("Biz");
		//判断用户名是否存在
		$arrBiz = $DbBiz->where("user_nickname = '$username'")->find();
		$passwordsha1 = sha1($password);
		if(empty($arrBiz)){
			$status = -1;
		}elseif($arrBiz['user_password'] != $passwordsha1){
			$status = -2;
		}else{
			$status = $arrBiz['user_id'];
		}
		if($status > 0){
			$passport = array();
			$passport = $arrBiz;
		}else{
			$passport = $status;
		}
	}
	
	return $passport;
}

//判断当前用户登录状态
function checkauth() {
	global $_SGLOBAL;
	if(cookie('auth')){
		@list($password, $uid) = explode("\t", authcode(cookie('auth'), 'DECODE'));
		$_SGLOBAL['G_uid'] = intval($uid);
		$_SGLOBAL['G_biz'] = cookie('biz');
		$_SGLOBAL['G_siteid'] = cookie('siteid');
		$_SGLOBAL['G_siteflag'] = cookie('siteflag');
		if($password && $_SGLOBAL['G_uid'] && $_SGLOBAL['G_biz'] == 'user'){
			$DbUser = M('User');
			$arrUser = array();
			$arrUser =  $DbUser->where("user_id = '".$_SGLOBAL['G_uid']."'")->find();
			if($arrUser){
				if($arrUser['user_password'] == $password){
					$_SGLOBAL['G_username'] = addslashes($arrUser['user_nickname']);
				}else{
					$_SGLOBAL['G_uid'] = 0;
				}
			}else{
				$_SGLOBAL['G_uid'] = 0;
			}
		}elseif($password && $_SGLOBAL['G_uid'] && $_SGLOBAL['G_biz'] == 'biz'){
			$DbBiz = M('Biz');
			$arrBiz = array();
			$arrBiz =  $DbBiz->where("user_id = '".$_SGLOBAL['G_uid']."'")->find();
			if($arrBiz){
				if($arrBiz['user_password'] == $password){
					$_SGLOBAL['G_username'] = addslashes($arrBiz['user_nickname']);
				}else{
					$_SGLOBAL['G_uid'] = 0;
				}
			}else{
				$_SGLOBAL['G_uid'] = 0;
			}
		}
	}
	
	if(empty($_SGLOBAL['G_uid'])){
		clearcookie();
	}
}

//清空cookie
function clearcookie(){
	global $_SGLOBAL;
	//清除当前前缀下的所有cookie
	cookie('auth',null);
	//全局变量置空
	$_SGLOBAL['G_uid'] = 0;
	$_SGLOBAL['G_username'] = '';
	$_SGLOBAL['G_biz'] = '';
	$_SGLOBAL['G_siteid'] = -1;
	$_SGLOBAL['G_siteflag'] = -1;

}

//判断用户身份
function checkstatus($status = 'user'){
	global $_SGLOBAL;
	$message = array();
	if(!$_SGLOBAL['G_uid'] && empty($_SGLOBAL['G_username'])){
		$message['flag'] = 1;
		$message['msg'] = "您还没有登录";
		cookie('_refer' , rawurlencode($_SERVER['REQUEST_URI']));
	}elseif($status == 'user' && $_SGLOBAL['G_biz'] != 'user'){
		$message['flag'] = 2;
		$message['msg'] = "此功能只限个人会员使用";
	}elseif($status == 'biz' && $_SGLOBAL['G_biz'] != 'biz'){
		$message['flag'] = 3;
		$message['msg'] = "此功能只限商户使用";
	}
	return $message;
}

//判断商业用户是否已经认领店铺
function checkhavesite(){
	global $_SGLOBAL;
	$message = '';
	if($_SGLOBAL['G_biz'] == 'biz'){
		if(empty ($_SGLOBAL['G_siteid']) || empty($_SGLOBAL['G_siteflag'])){
			$message = "您还没有店铺，或认领的店铺还在核审中。";
		}
	}else{
		$message = "非法操作";
	}
	return $message;
}

//字符串解密加密
function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) {

	$ckey_length = 4;	// 随机密钥长度 取值 0-32;
				// 加入随机密钥，可以令密文无任何规律，即便是原文和密钥完全相同，加密结果也会每次不同，增大破解难度。
				// 取值越大，密文变动规律越大，密文变化 = 16 的 $ckey_length 次方
				// 当此值为 0 时，则不产生随机密钥
	$key = md5($key ? $key : C('BUYPG_KEY'));
	$keya = md5(substr($key, 0, 16));
	$keyb = md5(substr($key, 16, 16));
	$keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : '';

	$cryptkey = $keya.md5($keya.$keyc);
	$key_length = strlen($cryptkey);

	$string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string;
	$string_length = strlen($string);

	$result = '';
	$box = range(0, 255);

	$rndkey = array();
	for($i = 0; $i <= 255; $i++) {
		$rndkey[$i] = ord($cryptkey[$i % $key_length]);
	}

	for($j = $i = 0; $i < 256; $i++) {
		$j = ($j + $box[$i] + $rndkey[$i]) % 256;
		$tmp = $box[$i];
		$box[$i] = $box[$j];
		$box[$j] = $tmp;
	}

	for($a = $j = $i = 0; $i < $string_length; $i++) {
		$a = ($a + 1) % 256;
		$j = ($j + $box[$a]) % 256;
		$tmp = $box[$a];
		$box[$a] = $box[$j];
		$box[$j] = $tmp;
		$result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
	}

	if($operation == 'DECODE') {
		if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)) {
			return substr($result, 26);
		} else {
			return '';
		}
	} else {
		return $keyc.str_replace('=', '', base64_encode($result));
	}
}

//获取用户信息
function getUserByUid($uid){
	$model = M('User');
	$User = $model->where("user_id = $uid")->find();
	return $User;
}

//判断用户签到状态
function isUserSign(){
	global $_SGLOBAL;
	$UserInfo = getUserByUid($_SGLOBAL['G_uid']);
	$TodayZero = strtotime(date("Y-m-d 00:00:00",time()));
	if($UserInfo['signtime'] > $TodayZero){
		$user_sign = 1;
	}else{
		$user_sign= 0;
	}

	return $user_sign;
}

//获取左侧分类，带缓存
function getLeftCategory(){
	if (S('leftcate')){
		$arrPrintCate = S('leftcate');
	} else{
		$DbCate = M("NbClass");
		$DbSite = M("NbSite");
		$arrResultCate = $DbCate->order('class_order desc')->select();
		foreach ($arrResultCate as $key=>$value){
			//查询当前分类下的10个网站按f7倒序
			$arrResultNbsite = array();
			$arrResultNbsite = $DbSite->where(' country_id = 0 and flag = 1 and class_id = '.$value['class_id'])->limit(10)->select();
			//格式化数据
			if($arrResultNbsite){
				foreach ($arrResultNbsite as $site_k => $site_v) {
					$arrResultNbsite[$site_k]['site_name'] = msubstr($site_v['site_name'], 0, 10, 'utf-8', FALSE);
					$arrResultNbsite[$site_k]['f7'] = formatFen($arrResultNbsite[$site_k]['f7']);
				}
			}
			$value['site'] = $arrResultNbsite;
			$arrPrintCate[$value['bigclass_id']][] = $value;
		}
		S('leftcate',$arrPrintCate,3600);
	}
	return $arrPrintCate;
}

//获取分类，带缓存
function getCategory(){
	if(S('category')){
		$arrCate = S('category');
	}else{
		$DbCate = M("NbClass");
		$arrCate = $DbCate->order('class_order desc')->select();
		S('category' , $arrCate , 3600);
	}
	return $arrCate;
}

//BlackList Website LeftCategory with cache
function getLeftCategory_blacklist(){
	if (S('leftcate_blacklist')){
		$arrPrintCate = S('leftcate_blacklist');
	} else{
		$DbCate = M("NbClass");
		$arrResultCate = $DbCate->order('class_order desc')->select();
		foreach ($arrResultCate as $key=>$value)
		{
			$arrPrintCate[$value['bigclass_id']][] = $value;
		}
		S('leftcate_blacklist',$arrPrintCate,3600*24*7);
	}
	return $arrPrintCate;
}

//News LeftCategory with cache
function getLeftCategory_news(){
	if (S('leftcate_news')){
		$arrPrintCate = S('leftcate_news');
	} else{
		$DbCate = M("NewsClass");
		$arrResultCate = $DbCate->order('class_order desc')->select();
		foreach ($arrResultCate as $key=>$value)
		{
			$arrPrintCate[] = $value;
		}
		S('leftcate_news',$arrPrintCate,3600*24*7);
	}
	return $arrPrintCate;
}

//Website class LeftCategory with cache
function getLeftCategory_nbclass(){
	if (S('leftcate_nbclass')){
		$arrPrintCate = S('leftcate_nbclass');
	} else{
		$DbCate = M("NbClass");
		$arrResultCate = $DbCate->order('class_order desc')->select();
		foreach ($arrResultCate as $key=>$value)
		{
			$arrPrintCate[$value['bigclass_id']][] = $value;
		}
		S('leftcate_nbclass',$arrPrintCate,3600*24*7);
	}
	return $arrPrintCate;
}

//showwindow class LeftCategory with cache
/*function getLeftCategory_showwindow(){
	if (S('leftcate_nbclass')){
		$arrPrintCate = S('leftcate_nbclass');
	} else{
		$DbCate = M("NbClass");
		$arrResultCate = $DbCate->order('class_order desc')->select();
		foreach ($arrResultCate as $key=>$value)
		{
			$arrPrintCate[$value['bigclass_id']][] = $value;
		}
		S('leftcate_nbclass',$arrPrintCate,3600*24*7);
	}
	return $arrPrintCate;
}*/

//International Website Index main cache
function getISiteMainCache()
{
    if(S('ISiteMainCache'))
    {
        $arrPrintCache = S('ISiteMainCache');
    }
    else
    {
        $arrNBClass = getCategory();
        $DbSite = M('NbSite');
        foreach ($arrNBClass as $key=>$value)
        {
            $tempClassId = $value['class_id'];
            $tResult = $DbSite->where("class_id = $tempClassId and country_id = 1")->limit(4)->select();
            if($tResult)
            {
                $value['site_list'] = $tResult;
                $arrPrintCache[] = $value;
            }
        }
        S('ISiteMainCache',$arrPrintCache,3600*24*7);
    }
    return $arrPrintCache;
}

//右侧专题 带缓存
function getRightZT(){
	if(S('rightzt')){
		$arrPrintZT = S('rightzt');
	}else{
		$DbZhuanTi = M('Zhuanti');
		$DbSite = M('NbSite');
		$arrResultZT = $DbZhuanTi->where('class_id = 0 and flag = 1')->order('zhuanti_id asc')->select();
		foreach ($arrResultZT as $key=>$value){
			$value['zhuanti_title'] = str_replace('网', '',$value['zhuanti_title']);
			$value['zhuanti_title'] .= "商城专题评价栏目";
			$arrResultNbsite = array();
			$arrResultNbsite = $DbSite->where('zhuanti_id = '.$value['zhuanti_id'])->order('site_id asc')->limit(10)->select();
			//格式化
			if($arrResultNbsite){
				foreach ($arrResultNbsite as $site_k => $site_v) {
					$arrResultNbsite[$site_k]['site_name'] = msubstr($site_v['site_name'], 0, 10, 'utf-8', FALSE);
					$arrResultNbsite[$site_k]['f7'] = formatFen($arrResultNbsite[$site_k]['f7']);
				}
			}
			$value['site'] = $arrResultNbsite;
			$arrPrintZT[] = $value;
		}
		S('rightzt' , $arrPrintZT, 3600);
	}
	return $arrPrintZT;
}

//分数格式化
function  formatFen($num){
	return $num = ($num % 10) ? number_format(floatval($num)/10, 1, '.', ' ') : $num/10;
}

//获取site_class的f1 至 f6的平均分
function getClassAvg($classid){
	$DbClass = M("ClassF");
	$arrClassAvg = $DbClass->field("f1_avg , f2_avg , f3_avg , f4_avg , f5_avg , f6_avg")->where("class_id = $classid")->find();
	return $arrClassAvg;
}

//获取site一个时段的f1 至 f6的平均分
function getSiteAvg($siteid,$sdate,$edate){
	$DbNbF = M("NbF");
	if(empty($sdate) && empty($edate)){
		$andwhere = "";
	}else{
		$andwhere = " and fdt > $sdate and fdt < $edate";
	}
	$arrNbF = $DbNbF->field("f1 , f2 , f3 , f4 , f5 , f6")->where("site_id = $siteid $andwhere")->select();
	$count = count($arrNbF);
	if($arrNbF){
		foreach ($arrNbF as $key => $value){
			$avgf1 += $arrNbF[$key]['f1'];
			$avgf2 += $arrNbF[$key]['f2'];
			$avgf3 += $arrNbF[$key]['f3'];
			$avgf4 += $arrNbF[$key]['f4'];
			$avgf5 += $arrNbF[$key]['f5'];
			$avgf6 += $arrNbF[$key]['f6'];
		}
	}
	return array('f1' => $avgf1/$count, 'f2' => $avgf2/$count, 'f3' => $avgf3/$count, 'f4' => $avgf4/$count, 'f5' => $avgf5/$count, 'f6' => $avgf6/$count);
}

//生成近6个月的折线图数据， 带缓存
function getZheXian($siteid){
	if(S('zhexiantu_data_'.$siteid)){
		$LineData = S('zhexiantu_data_'.$siteid);
	}else{
		$ThisMon = strtotime("now");
		$LastMon = array();
		$arrAvg = array();
		for ($i = 1; $i <= 6; $i++){
			//格式化过去1到6个月时间
			$LastMon[$i] = strtotime("-".$i." month");
			//获取过去1到6个月时间的f1 - f6的分数（“月”下的f1至f6的值）
			if($i == 1){
				$arrAvg[$i] = getSiteAvg($siteid, $LastMon[$i], $ThisMon);
			}else{
				$arrAvg[$i] = getSiteAvg($siteid, $LastMon[$i], $LastMon[$i-1]);
			}
		}
		//格式化数据（“f”下的过去1月到过去6月的值）
		$LineData = array();
		foreach ($arrAvg as $key => $value){
			$LineData['f1'][] = $arrAvg[$key]['f1'] ? ($arrAvg[$key]['f1'] > 95 ? $arrAvg[$key]['f1'] + rand(-5,0) : $arrAvg[$key]['f1'] + rand(-5,5)) : rand(70,95);
			$LineData['f2'][] = $arrAvg[$key]['f2'] ? ($arrAvg[$key]['f2'] > 95 ? $arrAvg[$key]['f2'] + rand(-5,0) : $arrAvg[$key]['f2'] + rand(-5,5)) : rand(70,95); 
			$LineData['f3'][] = $arrAvg[$key]['f3'] ? ($arrAvg[$key]['f3'] > 95 ? $arrAvg[$key]['f3'] + rand(-5,0) : $arrAvg[$key]['f3'] + rand(-5,5)) : rand(70,95); 
			$LineData['f4'][] = $arrAvg[$key]['f4'] ? ($arrAvg[$key]['f4'] > 95 ? $arrAvg[$key]['f4'] + rand(-5,0) : $arrAvg[$key]['f4'] + rand(-5,5)) : rand(70,95); 
			$LineData['f5'][] = $arrAvg[$key]['f5'] ? ($arrAvg[$key]['f5'] > 95 ? $arrAvg[$key]['f5'] + rand(-5,0) : $arrAvg[$key]['f5'] + rand(-5,5)) : rand(70,95); 
			$LineData['f6'][] = $arrAvg[$key]['f6'] ? ($arrAvg[$key]['f6'] > 95 ? $arrAvg[$key]['f6'] + rand(-5,0) : $arrAvg[$key]['f6'] + rand(-5,5)) : rand(70,95); 
		}
		S('zhexiantu_data_'.$siteid , $LineData , 3600*24*30);
	}
	return $LineData;
}

//生成雷达图数据带缓存
function getLeiDai($siteid){
	if(S('leidatu_data_'.$siteid)){
		$LeiDaData = S('leidatu_data_'.$siteid);
	}else{
		$arrSiteAvg = getSiteAvg($siteid);
		$DbSite = M("NbSite");
		$arrSite = $DbSite->field("class_id")->where("site_id = $siteid")->find();
		$arrClassAvg = getClassAvg($arrSite['class_id']);
		//格式化数据
		foreach ($arrSiteAvg as $value){
			$resultSiteAvg[] = formatFen($value);
		}
		foreach ($arrClassAvg as $value){
			$resultClassAvg[] = formatFen($value);
		}
		$LeiDaData = array('website_avg' => $resultSiteAvg, 'class_avg' => $resultClassAvg);
		S('leidatu_data_'.$siteid , $LeiDaData , 3600*24*30);
	}
	return $LeiDaData;
}

//获取当前时间(用于表单自动填充功能)
function getNowTime(){
	global $_SGLOBAL;
	return $_SGLOBAL['timestamp'];
}

//把获取的时间转换成字符串（用于表单自动填充功能）
function getTimeToStr(){
	$NowTime = getNowTime();
	return date("Y-m-d H:i:s", $NowTime);
}

//把获取的时间转换成字符串 仅Y-m-d（用于表单自动填充功能）
function getYmdToStr(){
	$NowTime = getNowTime();
	return date("Y-m-d", $NowTime);
}

//把<br>转换成nl用于在textarea显示
function Br2nl($string){
	return preg_replace("/<br\\s*?\/??>/i", "\n", $string);
}

//获取用户信息
function getUserInfo($value,$type='uid'){
	global $_SGLOBAL;
	if($type == 'uid'){
		$where = "user_id = '$value'";
	}elseif($type == 'username'){
		$where = "user_nickname = '$value'";
	}
	$DbUser = M("User");
	$arrUser = $DbUser->where($where)->find();
	
	return $arrUser;
}

//获取site的bigclass
function getBigClass($siteid){
	global $_SGLOBAL;
	$DbSite = M('NbSite');
	$DbClass = M('NbClass');
	$siteClassId = $DbSite->where('site_id = '.$siteid)->getField('class_id');
	$bigClassId = $DbClass->where('class_id = '.$siteClassId)->getField('bigclass_id');
	
	return $bigClassId;
}

//设置上传目录规则
function getDir(){
	global $_SGLOBAL;
	$NowTime = getNowTime();
	$dir1 = date("Y",$NowTime);
	$dir2 = date("m",$NowTime);
	$dir3 = date("d",$NowTime);
	return $dir1."/".$dir2."/".$dir3;
}

//获取alexa排名
function getAlexa($url,$siteid){
	if(S('Alexa_'.$siteid)){
		$arrAlexa = S('Alexa_'.$siteid);
	}else{
		import("@.ORG.Snoopy"); 
		$alexaURL = "http://data.alexa.com/data/+wQ411en8000lA?cli=10&dat=snba&ver=7.0&cdt=alx_vw=20&wid=12206&act=00000000000&ss=1680x1050&bw=964&t=0&ttl=35371&vis=1&rq=4&url=$url";
		$snoopy = new Snoopy;
		$snoopy->fetch($alexaURL);
		$content = $snoopy->results;
		$pattern = '/<POPULARITY URL="\s*(.+?)" TEXT="\s*(.+?)"\/>/'; /*在XML中匹配的<populartity />项里面的数据就是Alexa排名了 */
		$pattern2 = '/<CREATED DATE="\s*(.+?)" DAY="\s*(.+?)" MONTH="\s*(.+?)" YEAR="\s*(.+?)"\/>/'; /*在XML中匹配的<populartity />项里面的数据就是Alexa排名了 */
		preg_match($pattern2, $content, $dddd);
		preg_match($pattern, $content, $match); //进行匹配搜索
		$arrAlexa = array();
		if($dddd){
			$arrAlexa['date'] = $dddd[4] . "-" . $dddd[3] . "-" . $dddd[2] . ""; 
		}else{
			$arrAlexa['date'] = "--";
		}
		$arrAlexa['number'] = $match[2]; //$match[2] 就是排名了。
		S('Alexa_'.$siteid , $arrAlexa , 3600*24*30);
	}
	 
	return $arrAlexa;
}

function  getAlexaRank ($Domain){
	$line  = "";
	$data  = "";
	$URL  = "http://data.alexa.com/data/?cli=10&dat=snba&ver=7.0&url=". $Domain ;
	$fp  = fopen ($URL ,"r");
	if ($fp ){
		while (!feof ($fp )){
			$line  = fgets ($fp );
			$data  .= $line ; 
		}
		$p= xml_parser_create ();
		xml_parse_into_struct ($p , $data , $vals );
		xml_parser_free ($p );
		for ($i =0 ;$i <count ($vals );$i ++){
			if ($vals [$i ]["tag"]=="POPULARITY"){
				return  $vals [$i ]["attributes"]["TEXT"];    
			}
		}
	}
}

//搜索website
function searchWebsite($keyword,$limit,$order=''){
	$DbSite = M("NbSite");
	$arrkey = explode(" ",$keyword);
	$where['flag'] = array('eq' , 1);
	foreach($arrkey as $key => $value){
		if($key < 1){
			$where['_string'] = "(site_name like '%$value%')OR(site_desc like '%$value%')OR(site_link like '%$value%')";
		}else{
			$where['_string'] .= "OR(site_name like '%$value%')OR(site_desc like '%$value%')OR(site_link like '%$value%')";
		}
		
	}
	
	$arrSite = $DbSite->where($where)->order($order)->limit($limit)->select();

	return $arrSite;
}

//搜索news
function searchNews($keyword,$limit,$order=''){
	$DbNews = M("News");
	$arrkey = explode(" ",$keyword);
	foreach($arrkey as $key => $value){
		if($key < 1){
			$where['_string'] = "(news_title like '%$value%')OR(news_content like '%$value%')";
		}else{
			$where['_string'] .= "OR(news_title like '%$value%')OR(news_content like '%$value%')";
		}
	}
	
	$arrNews = $DbNews->where($where)->order($order)->limit($limit)->select();
	
	return $arrNews;
}

//搜索投诉
function searchTousu($keyword,$limit,$order=''){
	$DbTousu = M("NbTousu");
	$arrkey = explode(" ",$keyword);
	foreach($arrkey as $key => $value){
		if($key < 1){
			$where['_string'] = "(tousu_title like '%$value%')OR(tousu_content like '%$value%')";
		}else{
			$where['_string'] .= "OR(tousu_title like '%$value%')OR(tousu_content like '%$value%')";
		}
	}
	
	$arrTousu = $DbTousu->where($where)->order($order)->limit($limit)->select();
	
	return $arrTousu;
}

//获取优惠分类及分类下的推荐
function getYouHuiClass(){
	$YouHuiClassModel = M("YouhuiClass");
	$YouHuiClass = $YouHuiClassModel->where("status = 1")->select();
	$YouHuiClassRecommendModel= M("YouhuiClassRecommend");
	foreach($YouHuiClass as $key => $value){
		$YouHuiClassRecommend = $YouHuiClassRecommendModel->where("status = 1 and cid = ".$value['id'])->select();
		$YouHuiClass[$key]['Recommend'] = $YouHuiClassRecommend;
	}

	return $YouHuiClass;
}

//获取已经收录商家
function getIndexSite(){
	if (S('IndexSite')){
		$arrPrintSite = S('IndexSite');
	} else{
		$DbCate = M("NbClass");
		$DbSite = M("NbSite");
		$arrResultCate = $DbCate->order('class_order desc')->limit(14)->select();
		foreach ($arrResultCate as $key=>$value){
			//查询当前分类下的6个网站按f7倒序
			$arrResultNbsite = array();
			$arrResultNbsite = $DbSite->where(' country_id = 0 and flag = 1 and class_id = '.$value['class_id'])->limit(6)->select();
			$value['site'] = $arrResultNbsite;
			$arrPrintSite[] = $value;
		}
		S('IndexSite',$arrPrintSite,3600);
	}
	return $arrPrintSite;
}

//通过分类ID获取分类名
function getYouHuiClassNameByCid($cid){
	$YouHuiClassModel = M('YouhuiClass');
	$YouHuiClass = $YouHuiClassModel->where("id = $cid and status =1")->find();
	$name = $YouHuiClass['title'];
	return $name;
}

?>
